import { login, getUserInfo } from "@/api/sys";
import { setItem, getItem, remoteAllItems } from '@/utils/storage'
import { TOKEN } from "@/constant"
import router from "@/router";
import { setTimeStamp } from "@/utils/auth";
// 用于vuex缓存，和用户登录操作

export default {
    namespaced: true, // 表明是单独模块，不会进入主模块
    state: () => ({
        token: getItem(TOKEN) || '',
        userInfo: {}
    }),
    mutations: {
        // 存放token
        setToken (state, token){
            state.token = token
            // 存放到浏览器缓存中一份
            setItem(TOKEN, token)
        },
        setUserInfo (state, userInfo){
            state.userInfo = userInfo
        }
    },
    actions: {
        /**
         * 处理用户登录
         */
        login (context, userInfo){
            const { username, password } = userInfo
            return new Promise((resolve, reject) => {
                login({
                    username,
                    password
                }).then(data => {
                    this.commit('user/setToken', data.token)
                    console.log(data)
                    // 跳转
                    router.push('/')
                    // 保存登录时间
                    setTimeStamp()
                    resolve()
                }).catch(err => {
                    reject(err)
                })
            })
        },
        /**
         * 获取用户信息
         */
        async getUserInfo () {
            const res = await getUserInfo ()
            this.commit('user/setUserInfo', res)
            return res
        },
        /**
         * 退出登录
         */
        logout () {
            this.commit('user/setToken','')
            this.commit('user/setUserInfo',{})
            remoteAllItems()
            // TODO 清理掉权限相关配置
            router.push('/login')
        }
    }
}
